package com.bjc.cp.controller;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bjc.base.handler.MsgHandler;
import com.bjc.base.handler.SubscribeHandler;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * <pre>
 *  注意此controller类实现接口WxPayService（implements WxPayService ），
 *  仅是为了方便演示所有接口的使用，以免漏掉某一个新增加的接口，实际使用时无需如此实现。
 * </pre>
 *
 * @author Binary Wang
 */
@RestController
@RequestMapping("api/wx")
@Api(value = "wxCp-api", tags = { "微信认证相关接口" })
@Slf4j
public class WxCpController {

	@Autowired
	private WxMpService wxMpService;
	@Autowired
	private WxMpConfigStorage wxMpConfigStorage;
	@Autowired
	private WxMpMessageRouter wxMpMessageRouter;

	@PostConstruct
	public void init() {
		//关注消息
		wxMpMessageRouter.rule().async(false).event(WxConsts.EventType.SUBSCRIBE)
				.handler(new SubscribeHandler()).end();
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.EventType.VIEW)
				.handler(new MsgHandler()).next();
		

	}

	public Object checkOut(String signature, String nonce, String timestamp, final HttpServletRequest request) {

		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
			// 消息签名不正确，说明不是公众平台发过来的消息
			return new ResponseEntity<String>("非法请求", HttpStatus.OK);
		}
		String echostr = request.getParameter("echostr");
		if (StringUtils.isNotBlank(echostr)) {
			// 说明是一个仅仅用来验证的请求，回显echostr
			return new ResponseEntity<String>(echostr, HttpStatus.OK);
		}
		return null;

	}

	@RequestMapping(method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public Object reply(String signature, String nonce, String timestamp, final HttpServletRequest request) {
		try {
			String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw"
					: request.getParameter("encrypt_type");

			if ("raw".equals(encryptType)) {
				// 明文传输的消息
				WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
				WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
				return new ResponseEntity<String>(outMessage.toXml(), HttpStatus.OK);
			}

			if ("aes".equals(encryptType)) {
				// 是aes加密的消息
				String msgSignature = request.getParameter("msg_signature");
				WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpConfigStorage,
						timestamp, nonce, msgSignature);
				WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
				return new ResponseEntity<String>(outMessage.toEncryptedXml(wxMpConfigStorage), HttpStatus.OK);
			}
			return new ResponseEntity<String>("不可识别的加密类型", HttpStatus.OK);
		} catch (IOException e) {
			if (log.isInfoEnabled()) {
				log.info("微信消息异常", e);
			}
			return new ResponseEntity<String>("微信消息异常", HttpStatus.OK);
		}
	}
}
